package dao.impl;

import dao.ClientDao;
import dao.domain.Client;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author huangzhiyang
 * @Date 2023/11/7
 * @Description
 */
public class ClientDaoImpl extends BaseDaoImpl implements ClientDao {
    /**
     * 储存一个client对象到数据库
     *
     * @throws SQLException 数据库异常
     */
    @Override
    public void save(Client client) throws SQLException {
        String sql = "INSERT INTO `client` (account, NAME, PASSWORD, registrationTime, amount, Consumption) " +
                "VALUES (?, ?, ?, NOW(), ?, ?)";
        Connection connection = super.getConnection();
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, client.getAccount());
        statement.setString(2, client.getName());
        statement.setString(3, client.getPassword());
        statement.setDouble(4, client.getAmount());
        statement.setDouble(5, client.getConsumption());
        statement.executeUpdate();
        super.closeAll(connection, statement, null);

    }

    /**
     * 更新client
     *
     * @throws SQLException 数据库异常
     */
    @Override
    public void update(Client client) throws SQLException {
        String sql = "UPDATE `client` set " +
                "name=?, " +
                "password=?," +
                "amount=?" +
                ",consumption=?" +
                "where account=?";
        Connection conn = super.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, client.getName());
        pstmt.setString(2, client.getPassword());
        pstmt.setDouble(3, client.getAmount());
        pstmt.setDouble(4, client.getConsumption());
        pstmt.setString(5, client.getAccount());
        pstmt.executeUpdate();
        super.closeAll(conn, pstmt, null);
    }
}
